package com.crawler.harbour.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crawler.harbour.common.DockCode;
import com.crawler.harbour.dto.LoginParamsDto;
import com.crawler.harbour.entity.XmhtShipMent;
import com.crawler.harbour.model.Notice;
import com.crawler.harbour.model.ShipmentNew;
import com.crawler.harbour.service.INoticeService;
import com.crawler.harbour.service.IShipmentNewService;
import com.crawler.harbour.utils.AESUtil;
import com.crawler.harbour.utils.LoginUtil;
import com.crawler.harbour.utils.RuoKuai;
import com.crawler.harbour.utils.StorageDay;
import com.crawler.harbour.utils.StringUtils;
import com.crawler.harbour.utils.UrlUtil;
import com.crawler.utils.BeanUtils;
import com.crawler.utils.RedisManager;

import net.dongliu.requests.Parameter;
import net.dongliu.requests.Requests;
import net.dongliu.requests.Response;
import net.dongliu.requests.Session;

/**
 * 厦门海通
 *
 * @author wbsheng
 * @create 2018-04-02 9:25
 **/
@Service
@Lazy(false)
public class XMHTTask extends StorageDay{

    private static final Logger LOGGER = LoggerFactory.getLogger(XMHTTask.class);
    @Autowired
    IShipmentNewService shipmentNewService;

    @Autowired
    private INoticeService noticeService;
    /**
     * 每天01点30分执行
     * 厦门海通船期查询
     */
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void shipmentTask(){
    	if(!RedisManager.lock("ship:shipmentTask", 0)) {
    		return;
    	}
        Session session = Requests.session();
        //登入
        String jsTicket = LoginUtil.getJsTicket(session,LoginParamsDto.getLoginParams(UrlUtil.XMHTLOGIN,UrlUtil.XMHTVALIDATE,null,"GWHT_WEB_JsTicket"));
        System.out.println(jsTicket);
        //获取cookie数据
        Map<String, String> queryParam = new HashMap<>();
        queryParam.put("view", AESUtil.xhct("VesselScheduleQuery"));
        queryParam.put("encrpyCls", AESUtil.xhct("*"));
        //请求数据
        Response<String> queryResponse = session.post(UrlUtil.XMHTQUERY).forms(queryParam).headers(Parameter.of("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")).send().toTextResponse();
        String queryResponBody=queryResponse.getBody();
        JSONObject queryJsonObject = JSONObject.parseObject(queryResponBody);
        Integer total = queryJsonObject.getInteger("Total");
        JSONArray rows = queryJsonObject.getJSONArray("Rows");
        //转化成javabean
        List<XmhtShipMent> xmhtShipmentDtoList = JSONObject.parseArray(rows.toJSONString(), XmhtShipMent.class);
        List<ShipmentNew> shipmentNewList = new ArrayList<>();
        Date date=new Date();
        List<String> IdList =new ArrayList<>();
        for (XmhtShipMent shipMent : xmhtShipmentDtoList) {
        	ShipmentNew shipmentNew = new ShipmentNew();
        	 //取出出口，进口航次
            String voyage = shipMent.getVoyage();   
            String JkHangci = Judging(voyage, "进口");
            String CKHangci = Judging(voyage, "出口");
            Notice notice = new Notice();
            notice.setCreateTime(date);
            notice.setPortNo(DockCode._HT);
            shipmentNew.setWharfName("海通码头");
            shipmentNew.setSvcName(shipMent.getServiceRoute());
            shipmentNew.setOffLadingDate(shipMent.getCutOneTime());
            notice.setShipCnName(shipMent.getShipName());
            //取出出口，进口航次
            if(JkHangci != null) {
            	notice.setJkShipTimer(JkHangci);
            }
            if(CKHangci != null) {
            	notice.setCkShipTimer(CKHangci);
            } 
            notice.setCkSailingDate(StringUtils.nuller(shipMent.getPreMooringTime()));
            notice.setJkSailingDate(StringUtils.nuller(shipMent.getPreMooringTime()));
            notice.setIntoDate(StringUtils.nuller(shipMent.getAvailableTime()));
            notice.setOffDate(StringUtils.nuller(shipMent.getCutBoxTime()));
            notice.setBerthDate(StringUtils.nuller(shipMent.getPreMooringTime()));
            notice.setStatus(0);
            if(StringUtils.isBlank(notice.getShipName())) {
            	notice.setShipName(notice.getShipCnName());
            }
            notice.setCreateTime(date);
            BeanUtils.copyProperties(notice,shipmentNew , "id","status","type","shipTimer","sailingDate");
            String hashStr = null;
            ShipmentNew oldTemp1 =null;
            ShipmentNew oldTemp2 =null;
            if(JkHangci!=null) {
            	shipmentNew.setType(1);
            	hashStr = RuoKuai.MD5(DockCode._HT+shipMent.getShipName() + JkHangci+"_1");
            	shipmentNew.setId(hashStr);
            	shipmentNew.setShipTimer(JkHangci);
	            ShipmentNew temp = shipmentNewService.selectById(hashStr);
            	if (temp != null) {
            		oldTemp1= temp;
            	}
            	shipmentNew.setSailingDate(notice.getJkSailingDate());
            	 shipmentNewList.add(shipmentNew);
            }
            ShipmentNew shipmentNew2 = null;
            if(CKHangci!=null) {
            	shipmentNew2 = new ShipmentNew();
            	BeanUtils.copyProperties(shipmentNew,shipmentNew2);
            	shipmentNew2.setType(2);
            	shipmentNew2.setShipTimer(CKHangci);
            	hashStr = RuoKuai.MD5(DockCode._HT+shipMent.getShipName() + CKHangci+"_2");
            	shipmentNew2.setId(hashStr);
            	ShipmentNew temp = shipmentNewService.selectById(hashStr);
            	if (temp != null) {
            		oldTemp2= temp;
            	}
            	shipmentNew2.setSailingDate(notice.getCkSailingDate());
	            shipmentNewList.add(shipmentNew2);
            }
		    boolean isOk = true;
		    if(oldTemp1!=null&&IdList.contains(oldTemp1.getId())||oldTemp2!=null&&IdList.contains(oldTemp2.getId())) {
		        isOk = false;
		    }
            if(isOk) {
		              if (oldTemp1!=null &&!oldTemp1.getSailingDate().equals(StringUtils.nuller(shipMent.getPreMooringTime()))) {
		            	  if(StringUtils.nuller(oldTemp1.getSailingDate()).equals("")) {
		            		  notice.setType(0);
		            	  }else {
		            		  notice.setType(4);
		            	  }
		                  notice.setId(null);
		                  notice.setOrigValue(oldTemp1.getSailingDate());
		                  noticeService.insert(notice);
		              } 
		              if (oldTemp2!=null &&!oldTemp2.getSailingDate().equals(StringUtils.nuller(shipMent.getPreMooringTime()))) {
		            	  if(StringUtils.nuller(oldTemp2.getSailingDate()).equals("")) {
		            		  notice.setType(0);
		            	  }else {
		            		  notice.setType(1);
		            	  }
		                  notice.setId(null);
		                  notice.setOrigValue(oldTemp2.getSailingDate());
		                  noticeService.insert(notice);
		              } 
		              if (oldTemp2!=null &&!oldTemp2.getOffDate().equals(StringUtils.nuller(shipMent.getCutBoxTime()))) {
		                  notice.setType(2);
		                  notice.setId(null);
		                  notice.setOrigValue(oldTemp2.getOffDate());
		                  noticeService.insert(notice);
		              } 
		              if (oldTemp2!=null &&!oldTemp2.getIntoDate().equals(StringUtils.nuller(shipMent.getAvailableTime()))) {
		                  notice.setType(3);
		                  notice.setId(null);
		                  notice.setOrigValue(oldTemp2.getIntoDate());
		                  noticeService.insert(notice);
		              }
		              if(oldTemp1!=null) {
		            	  IdList.add(oldTemp1.getId());
		              }
		              if(oldTemp2!=null) {
		            	  IdList.add(oldTemp2.getId());
		              }
	         }
	              
        }
        LOGGER.info(total+" "+ xmhtShipmentDtoList.size());
        shipmentNewService.insertOrUpdateAllColumnBatch(shipmentNewList,xmhtShipmentDtoList.size());
        LOGGER.info("添加数据成功");
    }
    
    public String Judging(String parme,String patten) {
          Pattern compile = Pattern.compile("([^\\)]+)\\("+patten+"\\)");
          Matcher matcher = compile.matcher(parme);
          while(matcher.find()) {
             return matcher.group(1);
            }
          return null;
    }
}
